package com.xiaoxie.system.config;

import com.xiaoxie.common.utils.AESUtils;
import com.xiaoxie.system.datasource.DynamicDataSourceManager;
import com.xiaoxie.system.domain.Ds;
import com.xiaoxie.system.service.DsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class DataSourceInitializer implements CommandLineRunner {

    private final DsService dsService;

    private final DynamicDataSourceManager dynamicDataSourceManager;

    @Value("${crypto.secret}")
    private String secretKey;

    @Override
    public void run(String... args) throws Exception {
        log.info("动态数据源初始化开始...");
        // 获取所有的动态数据源
        List<Ds> dsList = dsService.selectAll("");

        // 把dsList中的密码进行解密操作后进行替换
        for (Ds ds : dsList) {
            ds.setPassword(AESUtils.decrypt(ds.getPassword(),secretKey));
        }

        // 创建数据源map
        Map<Object,Object> dataSourceMap = new HashMap<>();
        // 循环添加数据源
        for (Ds ds : dsList) {
            dataSourceMap.put(ds.getName(),dsService.getDataSource(ds));
        }
        // 设置目标数据源
        dynamicDataSourceManager.setTargetDataSources(dataSourceMap);
        dynamicDataSourceManager.afterPropertiesSet();
        log.info("数据源初始化完成...");
    }
}
